import pytest
import pymysql
import json

from api.shop_api import Api
from common.assert_tools import common_assert
from common.read_json_file import read_json_data



class TestShopRegister(object):
    data = read_json_data("../data/register_data.json")

    @pytest.mark.parametrize("desc,req_data,status_code,code,msg",data)
    def test01_register(self,desc,req_data,status_code,code,msg):
        resp = Api.register(req_data)

        # print(desc,":",resp.json())
        # 格式化输出，让测试结果更清晰
        print("\n" + "=" * 80)
        print(f"测试用例: {desc}")
        print(f"请求数据: {req_data}")
        print(f"响应结果: {resp.json()}")
        print(f"期望结果: HTTP状态码={status_code}, code={code}, msg={msg}")
        print("=" * 80)

        common_assert(resp,status_code,code,msg)

    def teardown_class(self):
        """测试类结束后自动清理测试数据"""
        print("\n开始清理测试数据...")

        # 连接数据库
        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
                               password='123456', database='tshop', charset='utf8')
        cursor = conn.cursor()

        try:
            # 读取测试用户名并删除
            with open('data/register_data.json', 'r', encoding='utf-8') as f:
                usernames = [item['req_data']['username'] for item in json.load(f)]

            deleted_count = 0
            for username in usernames:
                cursor.execute("DELETE FROM tshop.user WHERE username = %s", (username,))
                if cursor.rowcount > 0:
                    deleted_count += 1
                    print(f"已删除测试用户: {username}")

            conn.commit()
            print(f"清理完成！共删除 {deleted_count} 个测试用户")

        except Exception as e:
            print(f"清理失败: {e}")
            conn.rollback()
        finally:
            cursor.close()
            conn.close()
